package net.zwj.test.concurrent;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

public class MyRecursiveTask extends RecursiveTask<Integer> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6355372866938744758L;

	private int array[];

	private int start, end;

	public MyRecursiveTask(int array[], int start, int end) {
		this.array = array;
		this.start = start;
		this.end = end;
	}

	private Integer addResult() {
		int sum = 0;
		for (int i = start; i < end; i++) {
			sum += array[i];
		}
		return sum;
	}

	private Integer addResults(MyRecursiveTask task1, MyRecursiveTask task2)
			throws InterruptedException, ExecutionException {
		invokeAll(task1, task2);
		return task1.get().intValue() + task2.get().intValue();
	}

	@Override
	protected Integer compute() {
		Integer ret;
		MyWorkerThread thread = (MyWorkerThread) Thread.currentThread();
		thread.addTask();

		try {
			if (end - start < 10000) {
				ret = addResult();
			} else {
				int mid = (start + end) / 2;
				MyRecursiveTask task1 = new MyRecursiveTask(array, start, mid);
				MyRecursiveTask task2 = new MyRecursiveTask(array, mid, end);
				ret = addResults(task1, task2);
			}
			TimeUnit.MILLISECONDS.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
			ret = 0;
		} catch (ExecutionException e) {
			e.printStackTrace();
			ret = 0;
		}
		return ret;
	}

}
